#!/bin/bash
# File Name   : cg_sync.sh
# Author      : moshan
# Mail        : mo_shan@yeah.net
# Version     : 1.0
# Created Time: 2025-03-12 11:08:00
# Function    : cgroup脚本管理
#########################################################################
set -e -o pipefail

work_dir="/opt/soft/cgroup"
conf_dir="${work_dir}/conf"

localhost_ip="$(/sbin/ip a 2>/dev/null|grep inet|grep brd|grep scope|awk '{print $2}'|awk -F'/' '{print $1}'|head -1)" || true

. /etc/profile || true

env="${1}"

upgrade="${2}"

export PATH="/opt/soft/mysql80/bin:/opt/soft/mysql57/bin:${PATH}"

ssh_opt="-o ConnectTimeout=3 -o ConnectionAttempts=5 -o PasswordAuthentication=no -o StrictHostKeyChecking=no"

function f_main()
{
    if [ "${env}x" != "devx" ] && [ "${env}x" != "oltpx" ]
    then
        return 1
    else
        source ${conf_dir}/${env}.conf
    fi

    mysql_comm="${mysql_path} -u${mysql_user} -p${mysql_pass} -h${mysql_host} -P ${mysql_port} ${mysql_db}"
    is_master="$(timeout 10s ${mysql_comm} -NBe "show slave status\G" 2>/dev/null|wc -l)"
    if [ "${is_master}x" != "0x" ]
    then
        exit
    fi

    declare -a info_list

    sql="SELECT rshost
         from tb_cgroup_manager 
         where istate = 3 group by rshost;"

    if [ "${upgrade}x" == "upgradex" ]
    then
        sql="SELECT rshost
             from tb_cgroup_manager 
             where istate > 0 group by rshost;"
    fi

    info_list=($(echo "${sql}" |timeout 60s ${mysql_comm} -NB 2>/dev/null))
    echo "${info_list[@]}"
    for info in ${info_list[@]}
    do
        rshost="$(awk -F'@@@' '{print $1}' <<< "${info}")"

        rsync -r /work/moshan/gitlib/cgroup ${rshost}:/opt/soft/ || continue
        ssh ${rshost} 'rm -f /opt/soft/cgroup/test.sh'
        ssh ${rshost} 'rm -f /opt/soft/cgroup/*.lock'
        ssh ${rshost} 'rm -f /opt/soft/cgroup/*.back'
        cron="/var/spool/cron/root"
        ssh ${ssh_opt} ${rshost} "grep 'cg_monitor.sh' ${cron} || echo '*/1 * * * * cd /opt/soft/cgroup && flock --wait 5 -x lock/cg_monitor.lock -c \"bash cg_monitor.sh ${env}\"' >> ${cron}"
        ssh ${ssh_opt} ${rshost} "grep 'cg_manager.sh' ${cron} || echo '*/1 * * * * cd /opt/soft/cgroup && flock --wait 5 -x lock/cg_manager.lock -c \"bash cg_manager.sh ${env}\"' >> ${cron}"
    done
}

f_main
